package com.bkhc.product.repository;

import com.bkhc.product.entity.BrandProduct;
import com.bkhc.product.entity.Partner;
import com.bkhc.product.entity.PartnerBrand;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface PartnerBrandRepository extends JpaRepository<PartnerBrand,String>, JpaSpecificationExecutor<PartnerBrand> {

    default Page<PartnerBrand> findAll(PartnerBrand partnerBrand, Pageable pageable){
        return findAll(new Specification<PartnerBrand>() {
            @Override
            public Predicate toPredicate(Root<PartnerBrand> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(partnerBrand.getPartnerCode())){
                    predicate.add(criteriaBuilder.equal(root.get("partnerCode").as(String.class), partnerBrand.getPartnerCode()));
                }

                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);
    }
    PartnerBrand findByBrandCode(String brandCode);

    List<PartnerBrand> findByPartnerCode(String partnerCode);

    PartnerBrand findByBrandCodeAndProductCode(String brandCode, String productCode);

    @Modifying
    @Query("delete from PartnerBrand p where p.brandCode=:brandCode and p.productCode=:productCode")
    int deleteByBrandCodeAndProductCode(@Param("brandCode") String brandCode, @Param("productCode")String productCode);

    void deleteByPartnerCode(String partnerCode);

    List<PartnerBrand> findByBrandCodeAndPartnerCode(String brandCode, String partnerCode);
}
